#pragma once

#include "Log.hpp"
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace ns_netio
{
    #define SIZE 1024
    bool Recv(int sock, std::string &buffer)
    {
        char tmp[SIZE];
        ssize_t n = recv(sock, tmp, SIZE - 1, 0);
        if(n > 0)
        {
            tmp[n] = '\0';
            buffer += tmp;
            // std::cout << "buffer:" << buffer << std::endl;
            // std::cout << "buffer size:" << buffer.size() << std::endl;
            // std::cout << "tmp:" << tmp << std::endl;
            logMessage(NORMAL, "recieve message success\n");
            return true;
        }
        else if(n == 0)
        {
            logMessage(ERROR, "client close, server close, too\n");
            return false;
        }
        else 
        {
            logMessage(ERROR, "recieve message fail\n");
            return false;
        }
    }

    bool Send(int sock, const std::string& msg)
    {
        ssize_t n = send(sock, msg.c_str(), msg.size(), 0);
        if(n > 0)
        {
            logMessage(NORMAL, "send success!\n");
            return true;
        }
        else if(n == 0) 
        {
            logMessage(ERROR, "No message send!\n");
            return false;
        }
        else
        {
            logMessage(ERROR, "Send fail!\n");
            return false;
        }
    }
}